package cn.itcast.pc.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.itcast.controller.IpBean;
import cn.itcast.ft.dto.FtGoodsDTO;
import cn.itcast.ft.dto.FtOrderDTO;
import cn.itcast.ft.dto.FtTokenDTO;
import cn.itcast.ft.dto.PageGoodsdDetailDTO;
import cn.itcast.ft.entity.FTToken;
import cn.itcast.pc.dto.PCGoodsDTO;
import cn.itcast.pc.dto.PCListGoodsDTO;
import cn.itcast.pc.dto.PCOrderDTO;
import cn.itcast.utils.DingDingUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.*;

@RestController
@Slf4j
public class PCController {
    private static List<IpBean> list=new ArrayList<>();
    private static List<FTToken> tokenList=new ArrayList<>();
    @RequestMapping("/pcCreateMarket")
    public String pcCreateMarket(@RequestParam(value = "num",defaultValue = "10000") Integer num,
                               @RequestParam(value = "salePrice",defaultValue = "29") String salePrice,
                               @RequestParam(value = "goodsId",defaultValue = "24") String goodsId) {
        if(CollectionUtils.isEmpty(list)){
            try{
                IpBean ipBean1 = new IpBean();
                ipBean1.setIpAddress("117.160.250.132");
                ipBean1.setPort(8080);
                list.add(ipBean1);
            }catch (Exception e){
                IpBean ipBean=new IpBean();
                list.add(ipBean);
            }
        }
        if(CollectionUtils.isEmpty(tokenList)){
            addToken();
        }
        for(int i=0;i<num;i++){
            try {
                for(int j=0;j<list.size();j++){
                    for(int z=0;z<tokenList.size();z++){
                        IpBean ipBean=list.get(j);
                        Proxy proxy = null;
                        confireMarketOrder(proxy,tokenList.get(z),goodsId,salePrice);
                        Thread.sleep(2000);
                    }

                }
            } catch (Exception e) {
                log.error("#####异常####" + e.getMessage());
            }
        }
        log.info("####FT执行完成#####");
        return null;
    }
    public void confireMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice){
        try{
            createMarketOrder(proxy,token,goodsId,salePrice);
        }catch (Exception e){
            log.error("#####获取商品失败####"+e.getMessage()+"###"+token);
        }
    }
    public void createMarketOrder(Proxy proxy,FTToken token,String goodsId,String salePrice) throws InterruptedException {
        PCGoodsDTO goodsDTO=null;
        String result=null;
        try{
            JSONObject ret = new JSONObject();
            ret.putOnce("box_id",goodsId);
            ret.putOnce("filter_type","0");
            ret.putOnce("number_type","up");
            ret.putOnce("page","1");
            ret.putOnce("pagesize","100");
            ret.putOnce("price_type","up");
            Long timestamp = System.currentTimeMillis();
            String md5Str="box_id="+goodsId+"&domain=https://api.hnheyu.top&filter_type=0&key=MINGYANGB7D0C9D279892857DE5490AB856772FE&number_type=down&page=1&pagesize=100&pathinfo=/api/goods/boxSellItemList&price_type=up&timestamp="+timestamp;
            String sign= SecureUtil.md5(md5Str);
            String url="https://api.hnheyu.top/api/goods/boxSellItemList";
            result=
                    HttpRequest.post(url).
                            body(ret.toString()).
                            header("Timestamp",timestamp+"")
                            .header("sign",sign).
                            header("Token", token.getToken()).execute().body();
            goodsDTO= JSONUtil.toBean(result,PCGoodsDTO.class);
        }catch (Exception e){
            log.error("##获取商品数据异常###:"+e.getMessage()+"####返回数据：###"+result);
        }
        if(goodsDTO.getCode()==0){
            if(goodsDTO.getData()!=null && !CollectionUtils.isEmpty(goodsDTO.getData().getData())){
                List<PCListGoodsDTO> list=goodsDTO.getData().getData();
                for(PCListGoodsDTO detailDTO:list){
                        Proxy finalProxy = proxy;
                        ThreadUtil.execAsync(() -> {
                            saveOrder(finalProxy,token,detailDTO.getBox_id(),detailDTO.getBox_user_id(),detailDTO.getNumber(),detailDTO.getUser_id());
                        });
                        Thread.sleep(1000);
                }
            }
        }
    }
    public void saveOrder(Proxy proxy,FTToken token,String goodsId,String boxUserId,String number,String userId){
        PCOrderDTO responseDTO=null;
        String response=null;
        try{
            Map<String,String> ret=new HashMap<>(16);
            ret.put("box_id",goodsId);
            ret.put("box_user_id",boxUserId);
            ret.put("user_id",userId);
            ret.put("payType","2");
            ret.put("number",number);
            Long timestamp = System.currentTimeMillis();
            String md5Str="box_id="+goodsId+"&box_user_id="+boxUserId+"&domain=https://api.hnheyu.top&key=MINGYANGB7D0C9D279892857DE5490AB856772FE&number="+number+"&pathinfo=/api/goods/createOrder&payType=2&timestamp="+timestamp+"&user_id="+userId;
            String sign= SecureUtil.md5(md5Str);
            String url="https://api.hnheyu.top/api/goods/createOrder";
            response=
                    HttpRequest.post(url).
                            body(ret.toString()).
                            header("Timestamp",timestamp.toString())
                            .header("sign",sign).
                            header("Token", token.getToken()).execute().body();
            log.info("#####创建订单结果####"+response);
            responseDTO= JSONUtil.toBean(response, PCOrderDTO.class);
            if(responseDTO.getCode()==1){
                DingDingUtils.sendMsg("热浪您有一个新的订单，请赶紧支付");
                log.error("#####创建订单成功####"+response);
            }
        }catch (Exception e){
            log.error("###创建订单失败###:"+e.getMessage()+",goodsId:"+goodsId+":"+"##返回的参数信息##:"+response+",#######:"+token);
        }

    }
    public void addToken(){
        FTToken token=new FTToken();
        token.setToken("783a81f7-a7d6-456d-8ffa-1f4be488b936");
        token.setRefreshToken("vgFA7-ge2XGJCrkbBFc7nbOaCtg");
        token.setTime(Convert.toDate("2023-03-28 19:49:05"));
//        token.setTime(new Date(new Date().getTime() + 20*60*1000));
        tokenList.add(token);
    }

}
